Manon.icu

I'm here to make you a better developer by teaching you everything I know about building for the web.

Published 2021-04-15

React Fragments

React 还为我们提供了一种称为fragment的元素。

React 要求在单个“父”组件中返回所有返回的元素。

例如,我们不能返回两个同级元素,比如 h1 和组件中的段落:

// this syntax is invalid
// function MyComponent() {
//   return (
//     <h1>My header</h1>
//     <p>My paragraph</p>
//   );
// }
// valid syntax
function MyComponent() {
  return (
    <>
      <h1>My header</h1>
      <p>My paragraph</p>
    </>
  )
}

使用<React.Fragment></React.Fragment> or <></>可返回多个元素。

Comments

No Comments!